package com.iva.beam;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.NavigationHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.iva.beam.alumnos.LoginAlumnosBeam;
import com.iva.beam.profesor.LoginProfesoresBeam;
import com.iva.model.VwAlumnosUsuario;
import com.iva.model.VwRolUser;
import com.iva.service.findService;

@Component("loginMgmtBean")
public class LoginBean  implements Serializable{
	 /** The user name. */
    private String userName;
     
    /** The password. */
    private String password;
    /**
     * Gets the user name.
     *
     * @return the user name
     */
    public String getUserName() {
        return userName;
    }
 
    /**
     * Sets the user name.
     *
     * @param userName
     *            the new user name
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    /**
     * Gets the password.
     *
     * @return the password
     */
    public String getPassword() {
        return password;
    }
 
    /**
     * Sets the password.
     *
     * @param password
     *            the new password
     */
    public void setPassword(String password) {
        this.password = password;
    }
    
    
    @Autowired
    findService find;
 
    /** From the applicationContext-security.xml mapping. */
    @ManagedProperty(value="#{authenticationManager}")
    private AuthenticationManager authenticationManager = null;
    
   
    @Autowired 
    private ApplicationContext context;
	/**
     * Login.
     *
     * @return the string
     */
    public String login(){
    	String returnValue = null;     
    	
    	
    	LoginAlumnosBeam tabMenuAlumno = (LoginAlumnosBeam)context.getBean("loginAlumnosBeam");
    	LoginProfesoresBeam tabMenuProfesores = (LoginProfesoresBeam)context.getBean("loginProfesoresBeam");
    	
        System.out.println("entro como " + this.userName);
//        tabMenu.setALUMNO_CODIGO(this.getUserName());
        switch(this.redirectUser()){
        case 1: {
        	returnValue =tabMenuProfesores.dirige(0);
        }        	
        break;
        case 2:{
        	
        	returnValue =  tabMenuAlumno.dirige(0);
        }
        break;
//        case 3:{
//        	System.out.println("llega  a papa");
//        	returnValue =  this.parentTabMenuBean.Dirige(2);
//        }
//        break;
        }
        System.out.println(returnValue);
        return returnValue;
    }
    
    public String logout(){
    	FacesContext facesContext = FacesContext.getCurrentInstance();
    	HttpSession session = ( HttpSession ) facesContext.getExternalContext().getSession( true );
    	Object currentUser = session.getAttribute("dto"); 
    	if( currentUser != null){
    		System.out.println(currentUser.toString());
    		FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    		NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
    		nh.handleNavigation(facesContext, null, "index");
    	}
    	System.out.println("Context Name "+facesContext.getExternalContext().getContextName());
    	return "/pages/index";    	
    }
     
    /**
     * Cancel.
     *
     * @return the string
     */
    public String cancel() {
        return null;
    }
 
    public AuthenticationManager getAuthenticationManager() {
        return authenticationManager;
    }
 
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
 
    
    public int redirectUser(){
		List<VwAlumnosUsuario> listUsuarios = null;
        HttpSession session = ( HttpSession ) FacesContext.getCurrentInstance().getExternalContext().getSession( true );
        String queryUsuario = " where id.nombreUsuario='"+this.getUserName()+"'";
        listUsuarios = find.listVwAmistades(queryUsuario);
        for(VwAlumnosUsuario dto:listUsuarios){
        	
        	session.setAttribute("dto",dto);
        }
		int i = 0;
		String query = " where id.nombreUsuario = '" +this.getUserName()+ "'";
		List<VwRolUser> rolUser = find.listVwRolUser(query);
		for(VwRolUser usr:rolUser){
			if(usr.getId().getNombreRol().trim().equalsIgnoreCase("ROLE_TEACHER")){
				i = 1;
			}
			if(usr.getId().getNombreRol().trim().equalsIgnoreCase("ROLE_STUDENT")){
				i = 2;
			}
			if(usr.getId().getNombreRol().trim().equalsIgnoreCase("ROLE_PARENT")){
				i = 3;
			}
			else{
				System.out.println("Rol No Encontrado");
			}
			
		}
		return i;
	}
   
}